<template>
  <div class="staff">
    <p>职工管理</p>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="搜索">
        <el-input
          v-model="formInline.user"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">添加</el-button>
      </el-form-item>
    </el-form>

    <el-table
      border
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="staff_name" label="用户名"> </el-table-column>
      <el-table-column
        prop="staff_pass"
        label="密码"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="职位">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{
            scope.row.staff_status == "1" ? "员工" : "经理"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="staff_tel" label="联系电话"> </el-table-column>
      <el-table-column label="注册时间">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{
            scope.row.staff_createtime | dateFormat
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加弹出框 -->
    <div class="userModel">
      <div class="mask" v-show="userBoolean" @click="cancelModel">
        = false">
      </div>
      <div class="content" :class="userBoolean ? 'userContent' : ''">
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <h3>{{ modelTitle }}</h3>
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="ruleForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input
              type="password"
              v-model="ruleForm.pass"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input
              type="password"
              v-model="ruleForm.checkPass"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="staff_tel">
            <el-input v-model="ruleForm.staff_tel"></el-input>
          </el-form-item>
          <el-form-item label="用户类型" prop="staff_status">
            <el-radio-group v-model="ruleForm.staff_status">
              <el-radio :label="'1'">员工</el-radio>
              <el-radio :label="'2'">经理</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">
              {{ modelTitle }}</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getStaffList,
  addStaff,
  delStaff,
  staffDetail,
  changeStaff,
} from "../api/api";

export default {
  // 定义属性
  name: "Staff",
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      // console.log(value.length);
      setTimeout(() => {
        if (value.length < 2 || value.length > 6) {
          callback(new Error("请输入2-6个字符"));
        } else {
          callback();
        }
      }, 100);
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (value.length >= 4 && value.length <= 18) {
          callback();
        } else {
          callback(new Error("请输入6-18位密码"));
        }
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      formInline: {
        user: "",
        region: "",
      },
      tableData: [],
      multipleSelection: [],
      userBoolean: false,
      ruleForm: {
        pass: "",
        checkPass: "",
        userName: "",
        staff_status: "1",
        staff_tel:"",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        userName: [{ validator: checkAge, trigger: "blur" }],
        staff_status: [
          { required: true, message: "请选择用户类型", trigger: "change" },
        ],
        staff_tel: [
          { required: true, message: "请输入手机号", trigger: "change" },
        ],
      },
      total: 0,
      page: 1,
      size: 5,
      modelTitle: "添加",
      user_id: null,
    };
  },
  methods: {
    onSearch() {
      // console.log(this.formInline.user);
      this.getList();
    },
    onSubmit() {
      // console.log("submit!");
      this.modelTitle = "添加";
      this.userBoolean = true;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.getList();
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.ruleForm);
          // 添加
          if (this.modelTitle == "添加") {
            addStaff({
              staff_name: this.ruleForm.userName,
              staff_pass: this.ruleForm.pass,
              staff_status: this.ruleForm.staff_status,
              staff_tel: this.ruleForm.staff_tel,
            }).then((res) => {
              // console.log(res.data);
              if (res.code == 200)
                this.$message({
                  message: "恭喜你，添加成功",
                  type: "success",
                });
              this.getList();
              this.userBoolean = false;
            });
          } else if (this.modelTitle == "修改") {
            // 修改
            changeStaff({
              staff_id: this.staff_id,
              staff_name: this.ruleForm.userName,
              staff_pass: this.ruleForm.pass,
              staff_status: this.ruleForm.staff_status,
              staff_tel: this.ruleForm.staff_tel,
            }).then((res) => {
              console.log(res);
              if (res.code == 200) {
                this.$message({
                  message: res.messages,
                  type: "success",
                });
                this.userBoolean = false;
                // 刷新列表
                this.getList();
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getList() {
      getStaffList({
        page: this.page,
        size: this.size,
        staff_name: this.formInline.user,
      }).then((res) => {
        // console.log(res);
        this.tableData = res.data;
        this.total = res.total;
      });
    },
    // 删除
    handleDelete(index, row) {
      // console.log(index, row);
      delStaff({ id: row.staff_id }).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$message({
            message: "删除成功！",
            type: "success",
          });
          this.tableData.splice(index, 1);
        }
      });
    },
    // 编辑
    handleEdit(index, row) {
      // console.log(index, row);
      this.staff_id = row.staff_id;
      // 查询详情
      staffDetail({ id: row.staff_id }).then((res) => {
        if (res.code == 200) {
          this.ruleForm.userName = res.data.staff_name;
          this.ruleForm.pass = res.data.staff_pass;
          this.ruleForm.checkPass = res.data.staff_pass;
          // ?
          this.ruleForm.staff_status = res.data.staff_status;
          this.ruleForm.staff_tel = res.data.staff_tel;
          this.modelTitle = "修改";
          this.userBoolean = true;
        }
      });
    },
    cancelModel() {
      this.userBoolean = false;
      // 重置表单
      this.$refs["ruleForm"].resetFields();
    },
  },
  filters: {
    // 私有过滤时间的方法
    dateFormat(date) {
      var dt = new Date(date);
      var y = dt.getFullYear();
      var m = (dt.getMonth() + 1).toString().padStart(2, "0");
      var d = dt.getDate().toString().padStart(2, "0");
      var hh = dt.getHours().toString().padStart(2, "0");
      var mm = dt.getMinutes().toString().padStart(2, "0");
      var ss = dt.getSeconds().toString().padStart(2, "0");
      return `${y} - ${m} - ${d}  ${hh} : ${mm} : ${ss}`;
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getList();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
};
</script>

<style lang='scss' scoped>
.staff {
  width: 100%;
  margin: 20px;
  p {
    margin-bottom: 20px;
  }
  .userModel {
    .mask {
      position: fixed;
      left: 0;
      top: 0;
      z-index: 99;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.4);
    }
    .content {
      position: absolute;
      left: 50%;
      top: 0;
      transform: translateX(-50%);
      z-index: 100;
      background-color: #fff;
      transition: 0.5s;
      opacity: 0;
      padding: 30px 60px;
      border-radius: 10px;
      h3 {
        margin-bottom: 15px;
      }
      ::v-deep .el-form-item__label:before {
        content: "";
      }
    }
    .userContent {
      top: 15%;
      opacity: 1;
    }
  }
}
</style>